import api from "@/api";
import { listToTree } from "@/utils/listTotree";

export default {
  namespaced: true, // 模块
  state() {
    return {
      productCategoryList: [], // 列表结构的数据   以后要根据该数据转为树形结构
    };
  },
  getters: {
    productCategoryTree(state) {
      return listToTree(state.productCategoryList);
    },
    productCategoryTwoTree(state) {
      // let temp = state.productCategoryList.filter(
      //   (product) => product.level < 2
      // );
      return listToTree(
        state.productCategoryList.filter((product) => product.level < 2)
      );
    },
    getChildrenList(state) {
      return (id) => {
        return state.productCategoryList.filter(
          (product) => product.parent == id
        );
      };
    },
  },
  mutations: {
    // 修改列表结构数据
    getProductCategoryList(state, payload) {
      state.productCategoryList = payload;
    },
    createProductCategory(state, payload) {
      state.productCategoryList.push(payload);
    },
    editProductCategory(state, payload) {
      let index = state.productCategoryList.findIndex(
        (produce) => produce.id == payload.id
      );
      state.productCategoryList.splice(index, 1, payload);
      // state.productCategoryList[index] = payload // 绝对不行
    },
  },
  actions: {
    // 1、列表结构数据
    async getProductCategoryList({ commit }) {
      try {
        let { data } = await api.product.getProductCategoryList();
        commit("getProductCategoryList", data);
      } catch (err) {
        return Promise.reject(err);
      }
    },
    // 2、添加商品类别的方法
    async createProductCategory({ commit }, payload) {
      try {
        let { data } = await api.product.createProductCategory(payload);
        commit("createProductCategory", data);
        // return Promise.resolve(data);
        return data; // == Promise.resolve(data);
      } catch (err) {
        return Promise.reject(err);
      }
    },
    async editProductCategory({ commit }, payload) {
      try {
        let { data } = await api.product.editProductCategory(payload);
        console.log(data);
        commit("editProductCategory", data);
        // return Promise.resolve(data);
        return data; // == Promise.resolve(data);
      } catch (err) {
        return Promise.reject(err);
      }
    },
  },
};
